package cn.atcoder.air.config;

import cn.atcoder.air.msg.CallbackRequestMessage;
import cn.atcoder.air.msg.CallbackResponseMessage;
import cn.atcoder.air.msg.MessageBuilder;
import cn.atcoder.air.transport.ClientTransport;
import cn.atcoder.air.transport.ClientTransportFactory;

import java.lang.reflect.Proxy;

/**
 * @author yangjunda1
 * @description
 * @date 5/10/19 1:34 PM
 */
public class ConsumerConfig<T> {

    private transient volatile T proxyIns;

    private String interfaceId;

    private Class<T> clazz;

    private ClientTransport clientTransport;

    private int timeout = 1000;

    public synchronized T refer() {
        if (this.proxyIns != null) {
            return this.proxyIns;
        }
        this.clientTransport = ClientTransportFactory.refer();
        this.proxyIns = (T) newProxyInstance();
        return proxyIns;
    }

    /**
     * 创建一个代理对象
     */
    public Object newProxyInstance() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{clazz}, (proxy, method, args) -> {
                    CallbackRequestMessage requestMessage = MessageBuilder.buildCallbackRequest(interfaceId, method.getName(), args, method.getParameterTypes());
                    final CallbackResponseMessage responseMessage = (CallbackResponseMessage) clientTransport.send0(requestMessage, this.timeout);
                    return responseMessage.getBody();
                });
    }

    public String getInterfaceId() {
        return interfaceId;
    }

    public void setInterfaceId(String interfaceId) {
        this.interfaceId = interfaceId;
    }

    public Class<T> getClazz() {
        return clazz;
    }

    public void setClazz(Class<T> clazz) {
        this.clazz = clazz;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
}
